package cn.jdy.plugins.service;

import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jdy.framework.db.hibernate.BaseDao;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.StringUtil;
import cn.jdy.plugins.entity.BrandDiscuss;

/**
 * 品牌评论service 
 *
 * @author GXP
 */
@Service
public class BrandDiscussService extends BaseDao<BrandDiscuss> {

	/**
	 * 查询评论记录数
	 * @param bo
	 * @return
	 */
	public int getCount(BrandDiscuss bo){
		try {
      DetachedCriteria dc = DetachedCriteria.forClass(entityClass);
      dc.add(Restrictions.isNull("parentid"));
      if(!StringUtil.isNullOrEmpty(bo.getCompanyid()))  {
        dc.add(Restrictions.eq("companyid", bo.getCompanyid()));
      }
      if(!StringUtil.isNullOrEmpty(bo.getCompanyid()))  {
        dc.add(Restrictions.eq("username", bo.getUsername()));
      }
      return super.count(dc).intValue();
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询评论记录数失败！", e);
		}
		return 0;
	}
	
	/**
	 * 查询评论记录
	 * @param bo
	 * @return
	 */
	public List<BrandDiscuss> query(BrandDiscuss bo) {
		List<BrandDiscuss> list = null;
		try {

			String sql ="select id, status, disscuss_content,userip,username,discuss_type,is_anonymous,parentid,brandid,companyid,disscusstime ,(SELECT  b.companyName FROM company b  where b.id=t.companyid) as companyName ,(SELECT brandName  FROM companycontext brand WHERE  brand.companyid=t.companyid) as brandName  from branddiscuss t where t.parentid is null";
				if(!StringUtil.isNullOrEmpty(bo.getCompanyid()))
					sql+=" and  t.companyid = "+bo.getCompanyid();
				if(!StringUtil.isNullOrEmpty(bo.getUsername()))
					sql+=" and  t.username = "+bo.getUsername();
				if(!StringUtil.isNullOrEmpty(bo.getStatus()))
					sql+=" and  t.status = "+bo.getStatus();

				sql+=" order by t.disscusstime desc  limit "+bo.getiDisplayStart()+" , "+bo.getiDisplayLength();

			SQLQuery query = em().createSQLQuery(sql).addEntity(BrandDiscuss.class);
			list = query.list();
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询评论记录失败！", e);
		}
		return list;
	}

	/**
	 * 修改某一属性
	 *
	 * @param id
	 * @param attr
	 * @param value
	 * @return
	 */
	@Transactional
	public boolean updateSingleAttr(String id, String attr, Object value) {
		SQLQuery query = super.em().createSQLQuery("update branddiscuss set " + attr + " = :attr where id = :id");
		query.setParameter("attr", value);
		query.setParameter("id", id);
		return query.executeUpdate() > 0;
	}

}
